<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;

require_once '../extend/baidu.bos/BaiduBce.phar';
use BaiduBce\BceClientConfigOptions;
use BaiduBce\Util\MimeTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Services\Bos\BosClient;

class Base extends Controller
{
    public $page_info = [];
    public $exception = ['uploadsearch'];
    public $login_user = null;

    public function __construct(){
        parent::__construct();

        $login_user = session("cch_admin");
        $action = strtolower(request()->action());
        if(empty($login_user) && !in_array($action, $this->exception)){
            $this->redirect(url('admin/login'));
        }

        $this->login_user = $login_user;
        $this->page_info = [
            'action'=>$action,
            'controller'=>strtolower(request()->controller()),
            'path'=>request()->path()
        ];
        $this->page_info['controller'] = explode('/', $this->page_info['path'])[1];

        $configs = Db::name('config')->field('key,value')->select();
        $configs = arrayParamExtract($configs,'key','value');

        $this->assign([
            'login_user'=>$login_user,
            'Db'=>Db,
            'configs'=>$configs,
        ]);
    }

    /**
     * 上传图片
     * @Author   CCH
     * @DateTime 2020-08-15T17:26:24+0800
     * @return   [type]                   [description]
     */
    public function uploadLocal(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $filename = $file->getInfo()['name'];
            $ext = explode(".", $filename);//拆分获取图片名
            $ext = $ext[count($ext) - 1];//取图片的后缀名
            $ext = strtolower($ext);
            $types = ["jpg", "gif", 'png', 'bmp','jpeg','pdf','doc','docx','xls','xlsx','txt'];
            if (!in_array($ext, $types)) {
                return json(['code'=>5000,'msg'=>'文件格式不支持，请上传标准图片文件']);
            }
            $info = $file->move('./uploads');
            if($info){
                $result = [
                    'code'=>2000,'msg'=>'上传成功',
                    'extension'=>$ext,
                    'savename'=>str_replace('\\', '/', $info->getSaveName()),
                    'filename'=>$filename
                ];
                return json($result);
            }else{
                return json(['code'=>5000,'msg'=>$file->getError()]);
            }
        }
    }

    public function upload(){
        // $file = $_FILES['file'];
        // if (empty($file)) {
        //     return json(['code'=>5000,'msg'=>'未检测到图片']);
        // }
        // $ext = explode(".", $file['name']);//拆分获取图片名
        // $ext = $ext[count($ext) - 1];//取图片的后缀名
        // $ext = strtolower($ext);
        // $types = ["jpg", "gif", 'png', 'bmp','jpeg','pdf','doc','docx','xls','xlsx','txt'];
        // if (!in_array($ext, $types)) {
        //     return json(['code'=>5000,'msg'=>'文件格式不支持，请上传标准图片文件']);
        // }
        //调用配置文件中的参数
        $bos_config = config('config.baidu_bos');
        //新建BosClient
        $client = new BosClient($bos_config);
        $bucketName = $bos_config['bucket_name'];
        
        $file = $this->request->file('file');
        $ext = explode(".", $file->getInfo()['name']);//拆分获取图片名
        $ext = strtolower($ext[count($ext) - 1]);//取图片的后缀名
        $types = ["jpg", "gif", 'png', 'bmp','jpeg','webp','jfif'];
        if (!in_array($ext, $types)) {
            return json(['code'=>5000,'msg'=>'仅支持图片格式文件']);
        }
        // 将文件上传到本地
        $info = $file->move('uploads');
        $name_path =str_replace('\\',"/",$info->getSaveName());//文件存储的路径
        // $objectName = uuidCreate().'.'.$ext;
        $objectName = $file->getInfo()['name'];
        $result = $client->putObjectFromFile($bucketName, $objectName,'uploads/'.$name_path);

        $url = "uploads/".$info->getSaveName();//文件本地目录
        unset($info);//如果不释放这个变量下面的unlink()函数会报错。
        if (file_exists($url)) {
             unlink($url);//删除本地文件
        }

        $result = [
            'code'=>2000,'msg'=>'上传成功：'.$objectName,
            'extension'=>$ext,
            'savename'=>$bos_config['bos_url'].'/'.$objectName,
            'filename'=>$objectName
        ];
        return json($result);
    }

    public function uploadSearch(){
        //调用配置文件中的参数
        $bos_config = config('config.baidu_bos');
        //新建BosClient
        $client = new BosClient($bos_config);
        $bucketName = $bos_config['bucket_name'];
        
        $file = $this->request->file('file');
        $ext = explode(".", $file->getInfo()['name']);//拆分获取图片名
        $ext = strtolower($ext[count($ext) - 1]);//取图片的后缀名
        $types = ["jpg", "gif", 'png', 'bmp','jpeg','webp','jfif'];
        if (!in_array($ext, $types)) {
            return json(['code'=>5000,'msg'=>'仅支持图片格式文件']);
        }
        // 将文件上传到本地
        $info = $file->move('uploads');
        $name_path =str_replace('\\',"/",$info->getSaveName());//文件存储的路径
        $objectName = uuidCreate().'.'.$ext;
        $pathName = 'tmp_search/';
        $result = $client->putObjectFromFile($bucketName, $pathName.$objectName,'uploads/'.$name_path);

        $url = "uploads/".$info->getSaveName();//文件本地目录
        unset($info);//如果不释放这个变量下面的unlink()函数会报错。
        if (file_exists($url)) {
             unlink($url);//删除本地文件
        }

        $result = [
            'code'=>2000,'msg'=>'上传成功：'.$file->getInfo()['name'],
            'extension'=>$ext,
            'savename'=>$bos_config['bos_url'].'/'.$pathName.$objectName,
            'filename'=>$objectName
        ];
        return json($result);
    }

    public function uploadOss(){
        $file = $_FILES['file'];
        if (empty($file)) {
            return apiResult('5000','未检测到文件');
        }
        $result = uploadFile($file['name'],$file['tmp_name'],'appraisal/admin/');
        if ($result['status'] == 1) {
            return apiResult('2000','上传成功',[
                'extension'=>$ext,
                'savename'=>$result['data'],
                'filename'=>$file['name']
            ]);
        }else{
            return apiResult('5000',$result['msg']);
        }
    }

    public function index($map=[]){
    	$model = $this->model;
    	$page_param = [
    		'page'=>input('page',1),
    		'list_rows'=>input('page_size',20)
    	];
        // 显示筛选
        $this->assignSearchs();

        $order_field = input('order_field','id');
        $order_type = input('order_type','desc');
    	$list = $model->where($map)->order($order_field,$order_type)->paginate($page_param);
        $page = $list->render();
    	return view('index', [
            'list'=>$list->toarray(),
            'page'=>$page
        ]);
    }

    public function view($id){
        $model = $this->model;
        $data = $model->where('id',$id)->find();
        return view('view', [
            'data'=>$data
        ]);
    }

    public function saveData($save_data){
        $model = $this->model;
        if (request()->isPost()) {
            $t_fields = $model->getTableFields();
            if (!isset($save_data['ctime']) && in_array('ctime', $t_fields)) {
                $save_data['ctime'] = time();
            }
            // if (!isset($save_data['utime']) && in_array('utime', $t_fields)) {
            //     $save_data['utime'] = time();
            // }
            if ( $model->save($save_data) ) {
                $this->success("添加成功",url('index'));
            }else{
                $this->error("添加失败");
            }
        }

        $this->assignFields();
        return view(emptyDef($this->page_info['view'],'common/save'), [
            
        ]);
    }

    public function updateData($id,$save_data){
        $model = $this->model;
        if (request()->isPost()) {
            $t_fields = $model->getTableFields();
            if (!isset($save_data['utime']) && in_array('utime', $t_fields)) {
                $save_data['utime'] = time();
            }

            if ( $model->where('id',$id)->update($save_data) !== false ) {
                $this->success("编辑成功",url('index'));
            }else{
                $this->error("编辑失败");
            }
        }

        $this->assignFields();
        $data = $model->where('id',$id)->find();
        return view(emptyDef($this->page_info['view'],'common/save'), [
            'data'=>$data
        ]);
    }

    public function delete($id){
        $model = $this->model;
        if ( $model->where('id',$id)->delete() ) {
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }

    public function moreDelete($ids){
        $model = $this->model;
        if ( $model->where('id','in',$ids)->delete() ) {
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }

    public function changeData($id,$save_data){
        $model = $this->model;
        if ( $model->where('id',$id)->update($save_data) !== false ) {
            return ['status'=>1];
        }else{
            return ['status'=>0,'msg'=>'操作失败'];
        }
    }

    public function update(){
        $model = $this->model;
        $param = request()->param();    

        $ids = explode(',', $param['id']);
        unset($param['id']);
        $t_fields = $model->getTableFields();
        if (!isset($param['utime']) && in_array('utime', $t_fields)) {
            $param['utime'] = time();
        }

        if ( $model->where('id','in',$ids)->update($param) !== false ) {
            $this->success("编辑成功");
        }else{
            $this->error("编辑失败");
        }
    }

}
